<template>
  <div class="app-container">
    <el-button v-if="checkPermission(permissionRoles.gift_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加礼包</el-button>

    <el-table v-loading="listLoading" :data="list" class="mt-15" height="660" border>
      <el-table-column label="礼包ID" prop="id" width="60px" align="center"></el-table-column>
      <el-table-column label="礼包名称" prop="name" align="center"></el-table-column>
      <el-table-column label="礼包内容" prop="items_str" width="400px" align="center"></el-table-column>
      <el-table-column label="邮件标题" prop="title" width="140px" align="center"></el-table-column>
      <el-table-column label="邮件内容" prop="content" width="300px" align="center"></el-table-column>
      <el-table-column label="礼包码数量" prop="num" align="center"></el-table-column>
      <el-table-column label="已使用数量" prop="used_num" align="center"></el-table-column>
      <el-table-column label="领取次数" prop="times" width="60px" align="center"></el-table-column>
      <el-table-column label="领取限制" prop="days" width="60px" align="center"></el-table-column>
      <el-table-column label="开始时间" prop="start_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="结束时间" prop="end_dt" width="140px" align="center"></el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="90px">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.gift_edit)" type="text" size="small" title="编辑" @click="handleEdit(row)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.gift_del)" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="礼包名称" prop="name">
          <el-input v-model="dataForm.name" class="defaut-input" placeholder="请输入礼包名称" />
        </el-form-item>
        <el-form-item label="领取次数" prop="times">
          <el-input v-model="dataForm.times" class="defaut-input" placeholder="请输入领取次数" />
        </el-form-item>
        <el-form-item label="领取限制">
          <el-input v-model="dataForm.days" class="defaut-input" placeholder="请输入领取限制" />
        </el-form-item>
        <el-form-item label="开始时间" prop="start_dt">
          <el-date-picker
            v-model="dataForm.start_dt"
            type="datetime"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_dt">
          <el-date-picker
            v-model="dataForm.end_dt"
            type="datetime"
            style="width: 50%"
          />
        </el-form-item>
        <el-form-item label="邮件标题" prop="title">
          <el-input v-model="dataForm.title" class="defaut-input" placeholder="请输入邮件标题" />
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input v-model="dataForm.content" type="textarea" :autosize="{ minRows: 5, maxRows: 8}" />
        </el-form-item>
        <el-form-item label="发送人" prop="sender">
          <el-input v-model="dataForm.sender" class="defaut-input" placeholder="填写发送人" />
        </el-form-item>
        <el-form-item label="奖励内容">
          <el-row>
            <el-col :md="3"><el-button type="primary" class="add" icon="el-icon-plus" @click="productAdd">新增</el-button></el-col>
          </el-row>
          <el-row
            v-for="(item, index) in dataForm.items"
            :key="index"
            class="mt-5"
            :gutter="12"
          >
            <el-col :md="6">
              <el-select v-model="item.id" clearable filterable placeholder="请选择物品">
                <el-option
                  v-for="p in products"
                  :key="p.id"
                  :label="p.desc"
                  :value="p.id"
                />
              </el-select>
            </el-col>
            <el-col :md="8"><el-input v-model="item.num" placeholder="数量" /></el-col>
            <el-col :md="4"><el-button type="danger" icon="el-icon-delete" @click.prevent="remove(item)" /></el-col>
          </el-row>
        </el-form-item>

      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>
<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getGiftList, handleGift, deleteGift } from '@/api/operator'
import Pagination from '@/components/Pagination'
import { deepClone } from '@/utils'
import { getItemConfig } from '@/api/config'

const defaultItem = {
  id: '',
  name: '',
  times: '',
  days: '0',
  title: '',
  content: '',
  sender: '系统',
  start_dt: new Date(),
  end_dt: new Date(Date.now() + 86400 * 1000 * 30),
  num: '0',
  items: [{
    id: '',
    num: ''
  }]
}
export default {
  name: 'GiftList',
  components: { Pagination },
  data() {
    return {
      listLoading: false,
      permissionRoles: this.$store.state.user.permissionRoles,
      dataForm: Object.assign({}, defaultItem),
      rules: {
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      products: [],
      total: 0,
      list: [],
      dialogVisible: false,
      dialogType: 'new',
      textMap: {
        new: '新增',
        edit: '编辑'
      }
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      getGiftList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    async getItemConfig() {
      const res = await getItemConfig()
      this.products = res.data.items
    },
    productAdd(row) {
      if (this.dataForm.items.length === 6) {
        return
      }
      this.dataForm.items.push({
        id: '',
        num: ''
      })
    },
    remove(row) {
      var index = this.dataForm.items.indexOf(row)
      if (index !== -1) {
        this.dataForm.items.splice(index, 1)
      }
    },
    handleAdd() {
      this.getItemConfig()
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) {
      if (row.items === null) row.items = ''
      if (Array.isArray(row.items) === false) {
        if (row.items === '') {
          row.items = [{ id: '', num: '' }]
        } else {
          const items = JSON.parse(row.items)
          const a = []
          for (let i = 0; i < items.length; i++) {
            const o = { id: '', num: '' }
            o.id = items[i].itemId
            o.num = items[i].num
            a[i] = o
          }
          row.items = a
        }
      }
      if (row.title.substring(row.title.length - 3, row.title.length) === '...') {
        row.title = row.title.substring(0, row.title.length - 3)
      }
      if (row.content.substring(row.content.length - 3, row.content.length) === '...') {
        row.content = row.content.substring(0, row.content.length - 3)
      }

      this.getItemConfig()
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dataForm = deepClone(row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          handleGift(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteGift(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    }
  }
}
</script>

<style>
.el-tabs__header {
  margin: 0px;
}
</style>
